// FileManager.java
import java.io.*;
import java.util.List;
import java.util.Map;

public class FileManager {
    
    // 保存订单到文件
    public static void saveOrdersToFile(List<Order> orders, String filename) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            for (Order order : orders) {
                writer.println(order.toString());
            }
            System.out.println("订单数据已保存到: " + filename);
        } catch (IOException e) {
            System.err.println("保存文件时出错: " + e.getMessage());
        }
    }
    
    // 从文件加载订单
    public static void loadOrdersFromFile(List<Order> orders, String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                try {
                    Order order = Order.fromFileString(line);
                    orders.add(order);
                } catch (IllegalArgumentException e) {
                    System.err.println("解析订单数据出错: " + e.getMessage());
                }
            }
            System.out.println("已从文件加载 " + orders.size() + " 个订单");
        } catch (FileNotFoundException e) {
            System.out.println("订单文件不存在，将创建新文件");
        } catch (IOException e) {
            System.err.println("读取文件时出错: " + e.getMessage());
        }
    }
    
    // 保存顾客数据
    public static void saveCustomersToFile(Map<String, Customer> customers, String filename) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            for (Customer customer : customers.values()) {
                writer.println(customer.toFileString());
            }
            System.out.println("顾客数据已保存到: " + filename);
        } catch (IOException e) {
            System.err.println("保存顾客数据时出错: " + e.getMessage());
        }
    }
    
    // 加载顾客数据
    public static void loadCustomersFromFile(Map<String, Customer> customers, String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                try {
                    Customer customer = Customer.fromFileString(line);
                    customers.put(customer.getName(), customer);
                } catch (IllegalArgumentException e) {
                    System.err.println("解析顾客数据出错: " + e.getMessage());
                }
            }
            System.out.println("已从文件加载 " + customers.size() + " 个顾客");
        } catch (FileNotFoundException e) {
            System.out.println("顾客文件不存在，将创建新文件");
        } catch (IOException e) {
            System.err.println("读取顾客文件时出错: " + e.getMessage());
        }
    }
}
